package javaCode.chapter16.ticket;

/**
 * @author 徐州城
 * @version 1.0
 * 使用多线程，模拟三个窗口同时售票 100张
 */
public class SellTicket {
    public static void main(String[] args) {

        //测试
//        SellTicket01 ticket01 = new SellTicket01();
//        SellTicket01 ticket02 = new SellTicket01();
//        SellTicket01 ticket03 = new SellTicket01();
//
//        //这里会出现超卖现象
//        ticket01.start();//启动售票线程
//        ticket02.start();
//        ticket03.start();

        System.out.println("==使用实现接口方式来售票==");
        SellTicket02 sellTicket02 = new SellTicket02();

        new Thread(sellTicket02).start();//第一个线程
        new Thread(sellTicket02).start();//第二个线程
        new Thread(sellTicket02).start();//第三个线程

    }
}

//使用Thread方式
class SellTicket01 extends Thread{

    private static int ticketNum = 100;//让多个线程共享 num

    @Override
    public void run() {
        while (true){
            if (ticketNum <= 0 ){
                System.out.println(Thread.currentThread().getName() + " 窗口售票结束...");
                break;
            }

            //休眠50毫秒，模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票"
                + " 剩余票数=" + (--ticketNum));
        }
    }
}

//实现接口
class SellTicket02 implements Runnable{

    private int ticketNum = 100;//让多个线程共享 num

    @Override
    public void run() {
        while (true){
            if (ticketNum <= 0 ){
                System.out.println(Thread.currentThread().getName() + " 窗口售票结束... ");
                break;
            }

            //休眠50毫秒，模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票"
                    + " 剩余票数=" + (--ticketNum));
        }
    }
}
